package com.godyao.filters;

import com.godyao.mvcframework.annotations.Security;
import com.godyao.mvcframework.pojo.Handler;
import com.godyao.mvcframework.servlet.DispacherServlet;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.List;

/**
 * @author godyao
 * @date 2021/10/1
 */
public class PermissionFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest servletRequest1 = (HttpServletRequest) servletRequest;
        List<Handler> handlers = DispacherServlet.getHandlerMapping();
        Handler handler = getHandler(handlers, servletRequest1);
        String[] allowUser = getAllowedUser(handler);
        String username = servletRequest1.getParameter("username");
        if (username == null || "".equals(username)) {
            servletResponse.setCharacterEncoding("gb2312");
            servletResponse.getWriter().write("你无权限访问！！！");
            return;
        }
        if (!Arrays.asList(allowUser).contains(username)) {
            servletResponse.setCharacterEncoding("gb2312");
            servletResponse.getWriter().write("你无权限访问！！！");
            return;
        }
        filterChain.doFilter(servletRequest, servletResponse);
    }

    private Handler getHandler(List<Handler> handlers, HttpServletRequest servletRequest1) {
        if (handlers.isEmpty()) {return null;}
        String requestURI = servletRequest1.getRequestURI();
        for (Handler handler : handlers) {
            if (handler.getUrlPattern().matcher(requestURI).matches()) {
                return handler;
            }
        }
        return null;
    }


    private String[] getAllowedUser(Handler handler) {
        String[] allowedUser = new String[0];
        Object controllerObj = handler.getControllerObj();
        if (controllerObj.getClass().isAnnotationPresent(Security.class)) {
            Security annotation = controllerObj.getClass().getAnnotation(Security.class);
            allowedUser = annotation.value();
        }
        // 获取具体handler的allowUser
        Method method = handler.getMethod();
        if (method.isAnnotationPresent(Security.class)) {
            Security annotation = method.getAnnotation(Security.class);
            allowedUser = annotation.value();
        }
        return allowedUser;
    }

    @Override
    public void destroy() {

    }

}
